package JUC.fockjoin;

import java.util.concurrent.RecursiveTask;

/**
 * @author mubei
 * @date 2021/11/22
 * @description
 * 求和就算
 * 无脑for
 * forkjoin
 * Stream 并行流
 *
 * 如何使用
 */
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }


    @Override
    protected Long compute() {
        if(end - start < temp){
            Long sum = 0l;
            for (Long i = start; i <=end ; i++) {
                sum += i;
            }
            return sum;
        }else{
            // 分支合并计算
            long mid = (end - start)>>1 + start;
            ForkJoinDemo task1 = new ForkJoinDemo(start, mid);
            // 拆分任务 压入线程队列
            task1.fork();
            ForkJoinDemo task2 = new ForkJoinDemo(mid+1, end);
            task2.fork();
            return task1.join()+task2.join();
        }
    }
}
